<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.jxgy_delete"
                   @click="handleDelete">删 除
        </el-button>
        <UploadStyle
          ref="uploadStyle"
          v-if="screenShotDialogVisible"
          :visible="screenShotDialogVisible"
          :img-url="imgUrl"
          :proportion="proportion"
          @closeDialog="closeDialog"
          @getImgURL="getImgURL"
        />
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, add, update, remove} from "@/api/service/jxgy";
  import {mapGetters} from "vuex";
  import {contrastTime} from "@/util/validate";

  export default {
    data() {
      return {
        screenShotDialogVisible: false,
        imgUrl: "",
        _done: null,
        proportion: [118, 118],// 宽高的像素数组
        _uploadLoading: null,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "主键",
              prop: "id",
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }],
              hide:true,
              display:false
            },

            {
              label: "标题",
              prop: "jxqyTitle",
              search:true,
              overHidden:true,
              span:24,
              rules: [{
                required: true,
                message: "请输入标题",
                trigger: "blur"
              }],
              maxlength:50,
              showWordLimit:true
            },
            {
              label: "封面图片",
              prop: "jxqyPic",
              rules: [{
                required: true,
                message: "请输入封面图片",
                trigger: "blur"
              }],
              type: 'upload',
              loadText: '附件上传中，请稍等',
              limit:1,
              accept: "image/*",
              listType: 'picture-img',
              span: 24,
              propsHttp: {
                url:'link',
                name:'name',
                res: 'data'
              },
              action: '/api/localfiles/uploadPcFile',
              tip: '只能上传jpg/png文件，且不超过500kb',
              hide: true,
              uploadBefore: (file, done, loading, col) => {
                this.screenShotDialogVisible = true
                const fileReader = new FileReader()
                fileReader.onload = (res) => {
                  // 给图片裁切传递参数
                  this.imgUrl = res.target.result
                }
                fileReader.readAsDataURL(file)
                // 备份
                this._done = done
                this._uploadLoading = loading
                this.proportion = [118, 118]
              }
            },
            {
              label: "发布人",
              prop: "jxqyPublic",
              search:true,
              overHidden:true,
              rules: [{
                required: true,
                message: "请输入发布人",
                trigger: "blur"
              }],
              maxlength:50,
              showWordLimit:true
            },
            {
              label: "学校名称",
              prop: "schoolId",
              type: "tree",
              search:false,
              overHidden:true,
              rules: [{
                required: true,
                message: "请选择学校",
                trigger: "blur"
              }],
              dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
              props: {
                label: "xxName",
                value: "id"
              },
            },
            {
              label: "活动详情",
              prop: "jxqyDesc",

              span: 24,
              component: "avueUeditor",
              //wangEditor编辑的配置
              customConfig: {
                // lineHeights: ['1', '1.15', '1.6', '2', '2.5', '3']
              },
              //是否启用oss(qiniu/ali)
              oss:'',
              headers:{},
              data:{},
              // propsHttp: {
              //   home:'',
              //   url:'link',
              //   res: 'data'
              // },
              propsHttp: {
                url:'link',
                name:'name',
                res: 'data'
              },
              //普通图片上传
              action: '/api/localfiles/uploadPcFile',
              hide: true
            },
            {
              label: "开始时间",
              prop: "jxqyStart",

              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              overHidden:true,
              rules: [{
                required: true,
                message: "请输入开始时间",
                trigger: "blur"
              }]
            },
            {
              label: "结束时间",
              prop: "jxqyEnd",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              overHidden:true,
              rules: [{
                required: true,
                message: "请输入结束时间",
                trigger: "blur"
              }]
            },

            {
              label: "文章链接",
              prop: "jxqyUrl",
              span:24,
              // rules: [{
              //   required: true,
              //   message: "请输入文章链接",
              //   trigger: "blur"
              // }],
              hide: true,
              // maxlength:200,
              showWordLimit:true
            },
            {
              label: "二维码",
              prop: "jxqyQrcode",
              // rules: [{
              //   required: true,
              //   message: "请输入二维码",
              //   trigger: "blur"
              // }],
              accept: "image/*",
              type: 'upload',
              loadText: '附件上传中，请稍等',
              limit:1,
              listType: 'picture-img',
              span: 24,
              propsHttp: {
                url:'link',
                name:'name',
                res: 'data'
              },
              action: '/api/localfiles/uploadPcFile',
              tip: '只能上传jpg/png文件，且不超过500kb',
              hide: true
            },
            {
              label: "回放URL",
              prop: "jxqyRecUrl",
              span:24,
              rules: [{
                required: true,
                message: "请输入回放URL",
                trigger: "blur"
              }],
              hide: true,
              // maxlength:200,
              showWordLimit:true
            },
            {
              label: "直播URL",
              prop: "jxqyLiveUrl",
              span:24,
              // rules: [{
              //   required: true,
              //   message: "请输入直播URL",
              //   trigger: "blur"
              // }],
              hide: true,
              // maxlength:200,
              showWordLimit:true
            },
            {
              label: "活动状态",
              prop: "jxqyStatus",
              search:true,
              rules: [{
                required: true,
                message: "请输入活动状态",
                trigger: "blur"
              }],
              type: 'select',
              dicUrl: "/api/PcPublicService/GetDictionaryList?code=WENZHANGZHUANGTAI",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission","JSuserInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.jxgy_add, false),
          viewBtn: this.vaildData(this.permission.jxgy_view, false),
          delBtn: this.vaildData(this.permission.jxgy_delete, false),
          editBtn: this.vaildData(this.permission.jxgy_edit, false)
        };
      },
      schoolId(){
        return this.JSuserInfo.schoolId
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        if (!contrastTime(row.jxqyStart,row.jxqyEnd)) {
          this.$message({
            type: "warning",
            message: "开始时间不可大于结束时间!"
          });
          loading();
          return 0
        }
        row.id = '0'
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        console.log('row',row)
        if (!contrastTime(row.jxqyStart,row.jxqyEnd)) {
          this.$message({
            type: "warning",
            message: "开始时间不可大于结束时间!"
          });
          loading();
          return 0
        }
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove({ids:row.id});
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove({ids:this.ids});
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        console.log(type)
        // if (["edit", "view"].includes(type)) {
        //   // getDetail(this.form.id).then(res => {
        //   //   // res.data.data.jxqyDesc = "<p>\n\t12《<strong>森林防火员</strong>》</p><p>12《<strong>森林防火员</strong>》</p>"
        //   //   this.form = res.data.data;
        //   // });
        // }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        // params.SchoolId = this.schoolId
        // params.tenant_id = ''
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });

        const school = this.findObject(this.option.column, "schoolId");
        school.hide = true;
      },
      closeDialog(val){
        if(this._uploadLoading !== null){
          this._uploadLoading();
          this._uploadLoading = null
        }
        this.screenShotDialogVisible = val;
      },
      getImgURL(data){
        if(this._done !== null){
          this._done(data);
          this._done = null
        }
        this.closeDialog(false)
      }
    }
  };
</script>

<style>
</style>
